﻿// ******************* StonePonyApp *******************
// http://stackoverflow.com/questions/568784/jquery-modal-form-dialog-postback-problems
// http://www.ericmmartin.com/projects/simplemodal-demos/

//http://www.queness.com/post/1696/create-a-beautiful-looking-custom-dialog-box-with-jquery-and-css3
// TODO: why is it not included from external file? 
Type.registerNamespace('StonePonyApp');
StonePonyApp.Manager = function () {
    StonePonyApp.Manager.initializeBase(this);

    this._enquiryCount;
    this._currentImage;
    this._currentSessionId;
    this.CokieId;
    
    // Client's data
    this._FirstName;
    this._LastName;
    this._Phone;
    this._Email;
    this._Accept;
}
StonePonyApp.Manager.prototype = {
    initialize: function () {
        StonePonyApp.Manager.callBaseMethod(this, 'initialize');
        this._enquiryCount = 0;
        this._gallerificHeight;
        this._gallerificThumbCount;
        this._columnHeight;
        this._imageHeight;

        this.CokieId = 'Me_739A10F7_7329_4D70_BFA6_8F0AC5277188';
        this._readCookie();

        this._enquiryCount = $('input#EnquiredItemsCount').val();
        this._currentSessionId = $('input#SessionId').val();

        if (this._enquiryCount > 0) {
            $('div#myBasket div.MiddleTrashSection').show();
            $('div#myBasket img.ui-draggable').draggable({
                containment: 'parent',
                cursor: 'move',
                helper: 'clone'
            });
        }
        $('#logindisplay span.enquiryCounter').text(' ( ' + this._enquiryCount + ' ) ');
        this._gallerificThumbCount = 20;
    },

    dispose: function () {
        if (this._currentSessionId > 0 && this._enquiryCount > 0)
            this.sendEnquiry();
        StonePonyApp.Manager.callBaseMethod(this, 'dispose');
    },

    get_ConfirmationMessage: function () {
        var sb = new Sys.StringBuilder('This action will clear your selection');
        if (this._enquiryCount > 1)
            sb.append('s');
        sb.append('. Click OK to confirm your decision.');
        return sb.toString();
    },

    // Show popup dialog for the first time only.
    enquirySelectedItem: function (imageFooter) {
        if (this._enquiryCount < 1 || !this._FirstName || !this._LastName || !this._Email) {
            this.popupDialog();
        }
        else {
            var table1 = $('#dialog-message tableLayout');
            this.enquiryItem(table1);
        }
    },

    get_gallerificThumbCount: function () {
        return this._gallerificThumbCount;
    },

    get_currentImage: function () {
        return this._currentImage;
    },
    set_currentImage: function (value) {
        this._currentImage = value;
    },
    set_currentImageUrl: function (value) {
        $('#logindisplay a.showImageUrl').attr('href', value);
    },

    //Popup dialog
    popupDialog: function () {

        // get the screen height and width  
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        // calculate the values for center alignment
        var dialogTop = (maskHeight / 3) - ($('#dialog-box').height() / 2);
        var dialogLeft = (maskWidth / 2) - ($('#dialog-box').width() / 2);

        var table = $('#dialog-message form table tbody');
        if (this._FirstName)
            $(table).find('input[name="FirstName"]').val(this._FirstName);
        if (this._LastName)
            $(table).find('input[name="LastName"]').val(this._LastName);
        if (this._Phone)
            $(table).find('input[name="Phone"]').val(this._Phone);
        if (this._Email)
            $(table).find('input[name="Email"]').val(this._Email);

        // assign values to the overlay and dialog box
        $('#dialog-overlay').css({ height: maskHeight, width: maskWidth }).show();
        $('#dialog-box').css({ top: dialogTop, left: dialogLeft }).show();

    },

    // All mandatory fields are filled?
    // Invisible box (subsequent calls) consider as valid one.
    validateDialog: function (table) {
        if (this._enquiryCount > 0)
            return true;

        var sb = new Sys.StringBuilder();
        this._validateMandatoryFields(table, sb);
        this._validateEmailFields(table, sb);

        if (sb.isEmpty()) {
            $(table).siblings('div.ErrorMessage').empty();
            return true;
        } else {
            sb.appendLine('</ul>');
            $(table).siblings('div.ErrorMessage').html(sb.toString());
            return false;
        }
    },

    // Send Enquiry data to server
    enquiryItem: function (table) {
        $.ajax(
        {
            type: "POST",
            url: "Home/SubmitEnquiry",
            data: this._buildEnquiryData(table, this._currentImage),
            success: function (result) {
                if (result.Success) {
                    var thisManager = $find('StonePonyAppManager');
                    thisManager._enquiryCount = result.TotalEnquiries;
                    thisManager._currentSessionId = result.SessionId;
                    $('#hiddenBottomBlock span.hiddenBlock').css('display', 'inline-block');
                    $('#myBasket div.MiddleTrashSection').css('display', 'inline-block');
                    $('#logindisplay span.enquiryCounter').text(' ( ' + thisManager._enquiryCount + ' ) ');
                    thisManager.putEnquiryToBasket(result.EnquiredItem);
                    $('#dialog-overlay, #dialog-box').hide();

                    return true;
                }
                else {
                    var sb = new Sys.StringBuilder("Error on server side:");
                    sb.append(result.ErrorMessage);
                    alert(sb.toString());
                    $('#dialog-overlay, #dialog-box input:text').val('');
                    $('#dialog-overlay, #dialog-box').hide();
                    return false;
                }
            },
            error: function (req, status, error) {
                alert(error);
                alert("Sorry! Unknown communication error. Contact system administrator.");
                $('#dialog-overlay, #dialog-box').hide();
                return false;
            }
        });

    },

    sendEnquiry: function () {
        $.ajax(
        {
            type: "POST",
            url: "Home/SendEnquiry",
            data: this._buildSendEnquiryData(),
            success: function (result) {
                if (result.Success) {
                    var thisManager = $find('StonePonyAppManager');
                    thisManager._enquiryCount = 0;
                    thisManager._currentSessionId = -1;
                    thisManager.ClearScreen();
                    return true;
                }
                else {
                    var sb = new Sys.StringBuilder("Error on server side:");
                    sb.append(result.ErrorMessage);
                    alert(sb.toString());
                    var thisManager = $find('StonePonyAppManager');
                    thisManager._enquiryCount = 0;
                    thisManager._currentSessionId = -1;
                    thisManager.ClearScreen();
                    return false;
                }
            },
            error: function (req, status, error) {
                alert(req);
                alert(status);
                alert(error);
                alert("Sorry! Unknown communication error. Contact system administrator.");
                return false;
            }
        });
    },

    // ******************** Private functions ********************
    putEnquiryToBasket: function (descriptor)
    {
        if (!descriptor)
            return;

        $("<img></img>", {
            "src": descriptor.SmallImageUrl,
            "alt": descriptor.ItemTitle,
            "title": "Drag the image to trash for deleting " + descriptor.ItemTitle,
            "data-imageid": descriptor.ItemCode
            }
        ).css({
            "margin-left": "4px",
            "margin-bottom": "4px",
            "border-style": "solid",
            "border-width": "medium",
            "border-color": "#A4A4A4",
            "width": "64px",
            "height": "48px"
        }).appendTo('#myBasket').draggable({
            containment: 'parent',
            cursor: 'move',
            helper: 'clone'
        });
    },

    deleteEnquiry: function(itemCode)
    {
        $.ajax(
        {
            type: "POST",
            url: "Home/DeleteEnquiry",
            data: this._buildDeleteEnquiryData(itemCode),
            success: function (result) {
                var thisManager = $find('StonePonyAppManager');
                thisManager._enquiryCount = thisManager._enquiryCount - 1;
                if (thisManager._enquiryCount < 1) {
                    $('#hiddenBottomBlock span.hiddenBlock').css('display', 'none');
                    $('#myBasket div.MiddleTrashSection').css('display', 'none');
                }
                $('#logindisplay span.enquiryCounter').text(' ( ' + thisManager._enquiryCount + ' ) ');

                var argument = String.format('#myBasket img[data-imageid="{0:d}"]', itemCode);
                $(argument).remove();
                $('div#myBasket div.MiddleTrashSection img').attr("src", "Images/Full Trash.png");
                return true;
            },
            error: function (req, status, error) {
                var thisManager = $find('StonePonyAppManager');
                thisManager._enquiryCount = 0;
                thisManager._currentSessionId = -1;
                $('#hiddenBottomBlock span.hiddenBlock').css('display', 'none');
                $('#myBasket div.MiddleTrashSection').css('display', 'none');
                $('#logindisplay span.enquiryCounter').text(' ( ' + thisManager._enquiryCount + ' ) ');
                return true;
            }
        });
    },

    ClearScreen: function()
    {
        $('#hiddenBottomBlock span.hiddenBlock').css('display', 'none');
        $('#myBasket div.MiddleTrashSection').css('display', 'none');
        $('#logindisplay span.enquiryCounter').text(' ( 0 ) ');
        $('div#myBasket div.MiddleTrashSection img').attr("src", "Images/24-Empty Trash.png");
        $('div#myBasket img').remove();
        $('#dialog-overlay, #dialog-box').hide();
    },

    clearEnquiries: function () {
        $.ajax(
        {
            type: "POST",
            url: "Home/ClearEnquiry",
            data: this._buildSendEnquiryData(),
            success: function (result) {
                var thisManager = $find('StonePonyAppManager');
                thisManager._enquiryCount = 0;
                thisManager._currentSessionId = -1;
                thisManager.ClearScreen();
                return true;
            },
            error: function (req, status, error) {
                var thisManager = $find('StonePonyAppManager');
                thisManager._enquiryCount = 0;
                thisManager._currentSessionId = -1;
                thisManager.ClearScreen();
                return true;
            }
        });
    },

    Get_CurrentSessionId: function () {
        return this._currentSessionId;
    },

    _buildSendEnquiryData: function () {
        var sb = new Sys.StringBuilder("SessionId=");
        sb.append(this._currentSessionId);
        return sb.toString();
    },

    _buildDeleteEnquiryData: function (imageId) {
        var sb = new Sys.StringBuilder("ItemCode=");
        sb.append(imageId);
        sb.append('&SessionId=');
        sb.append(this._currentSessionId);

        return sb.toString();
    },

    _buildEnquiryData: function (table, imageId) {
        var sb = new Sys.StringBuilder("ItemCode=");
        sb.append(imageId);

        sb.append('&SessionId=');
        sb.append(this._currentSessionId);

        if (this._enquiryCount < 1) {
            this._FirstName = $(table).find('input[name="FirstName"]').val();
            this._LastName = $(table).find('input[name="LastName"]').val();
            this._Phone = $(table).find('input[name="Phone"]').val();
            this._Email = $(table).find('input[name="Email"]').val();
            this._Accept = $('#Accept').is(":checked") ? '1' : '0';
            if ($('#Remember').is(":checked"))
                this._createCookie();
        }

        sb.append('&FirstName=');
        sb.append(this._FirstName);

        sb.append('&LastName=');
        sb.append(this._LastName);

        sb.append('&Phone=');
        sb.append(this._Phone);

        sb.append('&Email=');
        sb.append(this._Email);

        sb.append('&Accept=');
        sb.append(this._Accept);

        return sb.toString();
    },

    _createCookie: function () {
        var data = { 
            FirstName: this._FirstName,
            LastName: this._LastName,
            Phone: this._Phone,
            Email: this._Email
        };
        $.cookie(this.CokieId, JSON.stringify(data), { expires: 30 });
    },

    _readCookie: function () {
        var sData = $.cookie(this.CokieId);
        if (sData) {
            var oData = JSON.parse(sData);
            this._FirstName = oData.FirstName;
            this._LastName = oData.LastName;
            this._Phone = oData.Phone;
            this._Email = oData.Email;
            $('#ClearCookieBtn').show();
        }
    },

    _validateMandatoryFields: function (table, sb) {
        $(table).find('th.mandatory').each(function (i) {
            var mandatoryBoxText = $(this).next().find('input:text').val();
            if (mandatoryBoxText == '') {
                var txt = $(this).text();
                if (txt.endsWith('*'))
                    txt = txt.substr(0, txt.length - 1);
                if (sb.isEmpty()) {
                    sb.appendLine('<p>Please fill in the following fields:</p>');
                    sb.appendLine('<ul>');
                }
                sb.append('<li>');
                sb.append(txt);
                sb.appendLine('</li>');
            }
        });
    },

    _validateEmailFields: function (table, sb) {
        var RegExEmail = /^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/;
        var i = 0;
        $(table).find('th.email').each(function (i) {
            var emailText = $(this).next().find('input:text').val();
            if (emailText != '' && !RegExEmail.test(emailText)) {
                var txt = $(this).text();
                if (txt.endsWith('*'))
                    txt = txt.substr(0, txt.length - 1);
                if (i < 1) {
                    if (!sb.isEmpty())
                        sb.appendLine('</ul>');
                    sb.appendLine('<p>Please correct addresses listed below:</p>');
                    sb.appendLine('<ul>');
                }
                sb.append('<li>');
                sb.append(txt);
                sb.appendLine('</li>');
                i++;
            }
        });
    }

}
StonePonyApp.Manager.registerClass('StonePonyApp.Manager', Sys.Component);



// Async Tracking code in Google Analytics
// See: http://code.google.com/apis/analytics/docs/tracking/asyncTracking.html
// Here enhanced version of the code published in http://mathiasbynens.be/notes/async-analytics-snippet

var _gaq = [['_setAccount', 'UA-6483791-12'], ['_trackPageview']];
(function (d, t) {
    var g = d.createElement(t),
        s = d.getElementsByTagName(t)[0];
    g.async = g.src = '//www.google-analytics.com/ga.js';
    s.parentNode.insertBefore(g, s);
} (document, 'script'));
